import Draw from '../../base/compose/draw'
import Rect from '../../base/compose/ext/rect'
import Block from '../../base/compose/block'
import Com from '../../base/com'
import { pickNumber, deepCopy } from '@/psoon/base/utils'
import mmpx from '@/psoon/pub/px2mm'
import { On } from '@/psoon/ext/decorators'
import PrintTpl from './template.hbs'
import DefConfig from './normalConfig'
import { onDtChange, onFsChange, onSclChange } from './methods/configsEvents'
import './style.scss'
import { isType } from '../../base/utils'
class PrintBlock extends Com.extend(Block, Draw, Rect){
  _block = true

  elEvents ={
    'click @': e => {
      this.setActive()
    }
  }
  // 记录block的所有参数
  _config = null

  on_dt_change = onDtChange
  on_fs_change = onFsChange
  on_scl_change = onSclChange

  constructor( infotype = 'text' ){
    super( PrintTpl )
    this.setConfig( DefConfig )
    this.setType( infotype )
  }

  setType( type ){
    this._config.tp = type
  }

  setActive(){
    if(!$(this.el).hasClass('active')){
      this.emit('active-block-change', this)
      $(this.el).addClass('active')
    }
  }

  getConfig(){
    return this._config
  }

  setConfig( config ){
    const that = this
    const obj = deepCopy(config)
    this._config = new Proxy(
      obj,
      {
        get ( target, key, receiver ) {
          return target[key]
        },
        set ( target, prop, value ) {
          const flg = that['on_' + prop + '_change'] && that['on_' + prop + '_change'](value)
          if( isType(flg, 'Undefined') || flg){
            return Reflect.set(...arguments)
          }
          return null
        }
      }
    )
  }

  clearActive(){
    $(this.el).removeClass('active')
  }

  get isBlock(){
    return this._block
  }

  get isActive(){
    return this.root.hasClass('active')
  }

  offset( offs ){
    if(offs.up){
      const top = mmpx.getNumber(this.el.style.top, 'px')
      this.el.style.top = mmpx.getNumber((top + offs.up), 'mm') + 'mm'
    }
    if(offs.left){
      const left = mmpx.getNumber(this.el.style.left, 'px')
      this.el.style.left = mmpx.getNumber(left + offs.left, 'mm') + 'mm'
    }
  }

  @On('drag-mousedown')
  dragMouseDown( ed ){
    ed && (ed.block = this )
    ed.elStartPos = {
      x: ed.block.el.style.left,
      y: ed.block.el.style.top
    }
  }

  @On('drag-mousemove')
  dragMousemove( ed ){
    const e = ed.e
    const start = ed.start
    const startPos = ed.elStartPos
    ed.block.el.style.left = mmpx.getNumber(startPos.x, 'mm') + mmpx.getNumber(e.pageX - start.x, 'mm') + 'mm'
    ed.block.el.style.top =  mmpx.getNumber(startPos.y, 'mm') + mmpx.getNumber(e.pageY - start.y, 'mm') + 'mm'
  }
  
  @On('drag-mouseup')
  dragMouseup( ed ){
    console.log(ed)
  }
}

export default PrintBlock